package org.hot100_6.leetcode102;

import org.leetcode.TreeNode;

import java.util.*;

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        forTree(root,res);
        return res;
    }

    public void forTree(TreeNode root,List<List<Integer>> res){

        if (root==null){
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);

        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size>0){
                TreeNode node = queue.poll();
                list.add(node.val);

                if (node.left!=null){
                    queue.add(node.left);
                }

                if (node.right!=null){
                    queue.add(node.right);
                }

                size--;
            }
            res.add(list);
        }

    }
}
